package org.ttitfly.ttcore.dao.account;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.QueryException;
import org.springframework.stereotype.Component;
import org.springside.modules.orm.hibernate.HibernateDao;
import org.ttitfly.ttcore.entity.account.User;
import org.ttitfly.ttcore.so.account.UserSO;
import org.ttitfly.ttcore.util.exception.DAOException;
import org.ttitfly.ttcore.util.query.ParameterResolver;
import org.ttitfly.ttcore.util.query.PropertyParameterResolver;
import org.ttitfly.ttcore.util.query.SQLBuilder;
import org.ttitfly.ttcore.util.query.SQueryBuilderByHibernate;

/**
 * 用户对象的泛型DAO类.
 * 
 * @author ttitfly
 */
@Component
public class UserDao extends HibernateDao<User, Long> {
	
	public int getSOUserViewCount(UserSO userSO) {
		return Integer.parseInt(getUsers4List(userSO, true).get(0).toString());

    }

    public List<User> getSOUserView(UserSO userSO) {
    	return getUsers4List(userSO,false);
    }
    
    @SuppressWarnings("unchecked")
    private <T> List<T> getUsers4List(UserSO so, boolean isCount) {
        SQLBuilder pattern = new SQLBuilder("select distinct o ");

        pattern
                .append("FROM User o  ");
        if (isCount) {
            pattern = new SQLBuilder("select count(distinct o) ");
            pattern.append("FROM User o");
        }

        pattern.append("and upper(o.loginName) like :%loginName% ");
        pattern.append("and upper(o.name) like :%name% ");
        pattern.append("and upper(o.email) like :%email% ");
        if (!isCount) {
        	pattern.append("[alias=o] order by {o.id} desc");
        }

        ParameterResolver resolver = new PropertyParameterResolver(so);
        Query query = null;
        try {
            query = SQueryBuilderByHibernate.buildQuery(getSession(), pattern.toString(), resolver);
        } catch (QueryException e) {
            throw new DAOException(e.getMessage());
        }

        return query.list();
    }

}
